package com.example.thirdhomework

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class ThirdActivity : AppCompatActivity() {
    var seconds = 0
    var running = false
    var wasRunning=false
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_third)
        Log.d("life cycle","")
        if(savedInstanceState!=null){
            seconds=savedInstanceState.getInt("seconds")
            running=savedInstanceState.getBoolean("running")
            wasRunning=savedInstanceState.getBoolean("wasRunning")
        }
        runTimer()

        val button_start = findViewById<Button>(R.id.button_start)
        button_start.setOnClickListener{
            running=true
        }
        val button_stop = findViewById<Button>(R.id.button_stop)
        button_stop.setOnClickListener{
            running=false
        }
        val button_restart=findViewById<Button>(R.id.button_restart)
        button_restart.setOnClickListener{
            running=true
            seconds=0
        }
    }
    fun runTimer(){
        val handle = Handler()
        val runnable=object : Runnable{
            override fun run() {
                val hours=seconds/3600
                val minutes = (seconds%3600)/60
                val secs=seconds%60
                val textView2_timer=findViewById<TextView>(R.id.textView2)
                textView2_timer.text=String.format("%02d:%02d:%02d",hours,minutes,secs)
                if(running){
                    seconds++
                }
                handle.postDelayed(this,1000)
            }
        }
        handle.post(runnable)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.d("life cycle","onSaveInstanceState")
        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasRunning",wasRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("life cycle","onDestroy")
    }

    override fun onStart() {
        super.onStart()
        Log.d("life cycle","onStart")
    }
    override fun onStop() {
        super.onStop()
        Log.d("life cycle","onStop")
    }

    override fun onResume() {
        super.onResume()
        Log.d("life cycle","onResume")
        if(wasRunning){
            running=true
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("life cycle","onPause")
        wasRunning=running
        running=false
    }
}